package com.example.tests;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.testng.annotations.DataProvider;

import com.example.data.GroupData;
import com.example.framework.ApplicationManager;

public class GroupDataGenerator {
	
	private static ApplicationManager manager;

	@DataProvider(name = "groups") 
	public static Iterator<Object[]> groups() {
		int numOfGroupsInList = 5;
		List<GroupData> groups=  new GroupDataGenerator().generateRandomGroupList(numOfGroupsInList);
		List<Object[]> list=  new ArrayList<Object[]>();
		for (GroupData group : groups) {
			list.add(new Object[]{group});
		}
		return list.iterator();
	}
	
	@DataProvider(name = "groupsFromFile") 
	public static Iterator<Object[]> loadGroupsFromFile() throws IOException {
		List<Object[]> list=  new ArrayList<Object[]>();
		manager = ApplicationManager.getInstance();
		String filename = manager.getProperties("groupCreationData");
		BufferedReader reader = new BufferedReader(new FileReader(filename));
		String line = reader.readLine();
		while (line != null) {
			String[] parts = line.split("\t");
			GroupData group = new GroupData().setName(parts[0])
					.setHeader(parts[1]).setFooter(parts[2]);
			list.add(new Object[]{group});
			line = reader.readLine();
		}
		return list.iterator();
	}
	public static void main(String[] args) {
		if (args.length <2) {
			System.out.println("Error: specify two parameters: file and count");
			return;
		}
		String file = args[0];
		int count = Integer.parseInt(args[1]);
		try {
			new GroupDataGenerator().generateDataToFile(file, count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void generateDataToFile(String fileName, int count) throws IOException {
		List<GroupData> groups = generateRandomGroupList(count);
		File file = new File(fileName);
		if (file.exists()) {
			System.out.println("File exists. Stopping generator");
			return;
		}
		FileWriter writer = new FileWriter(file);
		for (GroupData group : groups) {
			writer.write(group.name + "\t" + group.header + "\t" + group.footer + "\n");
			writer.flush();
		}
		writer.close();
	}

	private List<GroupData> generateRandomGroupList(int count) {
		List<GroupData> list=  new ArrayList<GroupData>();
		for (int i = 0; i < count; i++) {
			int lengthOfString = 5;
			GroupData group = new GroupData()
			.setName("name" + TestBase.generateAlphaNumbericRandom(lengthOfString))
			.setHeader("header" + TestBase.generateAlphaNumbericRandom(lengthOfString))
			.setFooter("footer" + TestBase.generateAlphaNumbericRandom(lengthOfString));
			list.add(group);
		}
		return list;
	}
}
